package br.com.zuq.geocode;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrQuery;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author zuq
 */
public class SolrGeocodeService implements GeocodeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SolrGeocodeService.class);
    private SolrServer server;

    public SolrGeocodeService() {
        try {
            server = new CommonsHttpSolrServer("http://localhost:8983/solr");
        } catch (MalformedURLException ex) {
            LOGGER.error("ERRO!", ex);
        }
    }

    public List<GisObject> findStreet(String name) {

        List<GisObject> result = new ArrayList<GisObject>();

        LOGGER.debug("Querying street " + name);

        SolrQuery query = new SolrQuery(name);
        query.setQueryType("dismax");
        query.setFields("*", "score");

        try {

            QueryResponse response = server.query(query);

            GisObject obj;

            for (SolrDocument doc : response.getResults()) {
                obj = new GisObject();
                obj.gid = Long.parseLong(doc.get("gid").toString());
                obj.name = doc.get("name").toString();
                obj.altname = getKeyValue("altname", doc);

                obj.tags = getTags(doc);

                // TODO isIn;
                
                result.add(obj);
            }

        } catch (SolrServerException ex) {
            LOGGER.error("Error when performing query: ", ex);
        }

        return result;
    }

    private String getKeyValue(String key, SolrDocument doc) {
        Object val = doc.get(key);
        return (val == null) ? "" : val.toString();
    }

    private Map<String, String> getTags(SolrDocument doc) {
        
        Map<String, String> result = new HashMap<String, String>();

        Object tags = doc.get("tags");
        
        if (tags == null) {
            return result;
        }

        if (tags instanceof String) {
            String[] split = tags.toString().split("#");

            result.put(split[0], split[1]);
        } else {

            List<String> tagList = (ArrayList) tags;

            for (String tag : tagList) {
                String[] split = tag.split("#");

                result.put(split[0], split[1]);
            }
            
        }

        return result;

    }
}
